import {
    materialAdd,
    materialDel,
    materialPage,
    materialUpdate,
} from "@/api/device/cycleManagement";

import type {FormInstance, FormRules} from "element-plus";
import {ElMessage} from "element-plus";
import {onMounted, ref} from "vue";

interface materiaLRecord {
    id: string;
    createTime?: string;
    updateUser?: string;
    updateTime?: string;
    createUser?: string;
    materiaLingCode: string;
    materiaLingType: string;
    materiaLingInventoryType?: string; // 新建字段
    description?: string;
    activate?: boolean;
    isDeleted?: boolean;
    clazz?: string;
    materialType?: string;
    materialName?: string;
    materialNo?: string;
    materialProperties?: string;
    basicUnit?: string;
    conversionUnit?: string;
    weightNumConvert?: string;
}

interface materialPageResult {
    records: materiaLRecord[];
    total: number;
    size: number;
    current: number;
    optimizeCountSql: boolean;
    searchCount: boolean;
    pageSize: number;
}

interface ApiResponse<T> {
    code: number;
    message: string;
    data: T;
}

interface PaginationParams {
    current: number;
    pageSize: number;
}

interface FormData {
    name: string;
    code: string;
    cycleStartDate: [string, string];
    triggerCycleType: string | number;
    invokeFrequency: number;
    advanceDate: number;
    invokeBegin: string | number;
    triggerTime: string;

    [key: string]: any;
}

export function useMaterialata() {
    const searchParam = ref({});
    const isLoading = ref(true);
    const searchFields = ref([
        {
            name: "name",
            label: "周期名称",
            component: "input",
            placeholder: "",
            class: "!w-[350px]",
        },
        {
            name: "code",
            label: "周期编码",
            component: "input",
            placeholder: "",
            class: "!w-[350px]",
        },
    ]);
    const week = [
        {label: 1, value: "星期一"},
        {label: 2, value: "星期二"},
        {label: 3, value: "星期三"},
        {label: 4, value: "星期四"},
        {label: 5, value: "星期五"},
        {label: 6, value: "星期六"},
        {label: 7, value: "星期日"},
    ];
    const restForm = ref({
        name: '',
        code: '',
        cycleStartDate: ['', ''],
        triggerCycleType: 1,
        invokeFrequency: 0,
        advanceDate: 0,
        invokeBegin: '',
        triggerTime: '',
    });
    const pageTotal = ref(0);
    const paginatedData = ref<materiaLRecord[]>([]);
    const paginationParams = ref<PaginationParams>({current: 1, pageSize: 10});
    const formData = ref<FormData>(restForm.value);
    const moldType = ref()
    const ruleFormRef = ref<FormInstance>(); // 表单实例引用

    const rules = ref<FormRules<FormData>>({
        name: [{required: true, message: '请输入周期名称', trigger: 'blur'}],
        code: [{required: true, message: '请输入周期编码', trigger: 'blur'}],
        cycleStartDate: [{required: true, message: '请选择周期有效期', trigger: 'change'}],
        triggerCycleType: [{required: true, message: '请选择周期类型', trigger: 'change'}],
        invokeFrequency: [
            {required: true, message: '请输入周期间隔', trigger: 'change'},
        ],
        advanceDate: [
            {required: true, message: '请输入提前生成天数', trigger: 'change'},

        ],
        invokeBegin: [{required: true, message: '请选择执行开始周期', trigger: 'change'}],
        triggerTime: [{required: true, message: '请选择执行开始时刻', trigger: 'change'}]
    });
    const fetchPageData = async (params: any) => {
        isLoading.value = true;
        try {
            const response = (await materialPage({
                ...params,
                type: params.type || moldType.value,
            })) as unknown as ApiResponse<materialPageResult>;

            if (response.code === 200) {
                const {records, total} = response.data;
                paginatedData.value = records.map((item) => {
                    return {
                        ...item.extension,
                        ...item,
                    };
                });
                pageTotal.value = total;
            } else {
                ElMessage.error(response.message);
            }
        } catch (error) {
            ElMessage.error("数据获取失败");
        } finally {
            isLoading.value = false; // 数据加载完成后设置为 false
        }
    };

    // onMounted(() => {
    //   fetchPageData(searchParam.value);
    // });

    const handleSearch = () => {
        fetchPageData(searchParam.value);
    };

    const handleSizeChange = (val: number) => {
        paginationParams.value.pageSize = val;
        fetchPageData(searchParam.value);
    };

    const handleCurrentChange = (val: number) => {
        paginationParams.value.current = val;
        fetchPageData(searchParam.value);
    };

    const addmateriaL = async (
        data: Partial<materiaLRecord>,
        callback: () => void
    ) => {
        if (ruleFormRef.value) {
            await ruleFormRef.value.validate(async (valid) => {
                if (valid) {
                    let params = {
                        ...data,
                        invokeBegin: JSON.stringify(data.invokeBegin),
                    };

                    const url = data?.id ? materialUpdate : materialAdd;
                    const response = (await url(params)) as unknown as ApiResponse<void>;
                    if (response.code === 200) {
                        if (data?.id) {
                            ElMessage.success("更新成功");
                        } else {
                            ElMessage.success("添加成功");
                        }
                        fetchPageData(searchParam.value);
                        callback();
                    } else {
                        ElMessage.error(response.message);
                    }
                }
            });
        }
    };

    const deletemateriaL = async (id: string) => {
        try {
            const response = (await materialDel({
                ids: [id],
            })) as unknown as ApiResponse<void>;
            if (response.code === 200) {
                ElMessage.success("删除成功");
                fetchPageData(searchParam.value);
            } else {
                ElMessage.error(response.message);
            }
        } catch (error) {
            ElMessage.error("删除失败");
        }
    };

    return {
        searchParam,
        pageTotal,
        paginatedData,
        searchFields,
        isLoading,
        week,
        handleSearch,
        handleSizeChange,
        handleCurrentChange,
        addmateriaL,
        deletemateriaL,
        fetchPageData,
        paginationParams,
        ruleFormRef,
        rules,
        formData,
        restForm,
        moldType
    };
}
